package com.udi.project.business.utils.check;


import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * @author Admin
 * GS1校验码计算
 */
@Component
public class CheckCodeUtils {

    /**
    *
     * @Description:校验码计算工具
     * @param all DI码
     * @return: java.lang.Integer 校验码
     * @Date: 2021/8/9 9:19
     */
    public Integer CheckCode(BigInteger all){
        String str = all.toString();
        System.out.println("要生成的DI码----------》"+str);
        String bit = str.substring(0,2);
        int[] code = new int[str.length()];
        for (int i=0; i<code.length; i++){
            code[i] = str.charAt(i)-'0';
        }
        int combine = 0;
        if("69".equals(bit)){
            //偶数
            int even = 0;
            //奇数
            int oddNumber = 0;
            for(int i=0;i<code.length;i++){
                if(i % 2 == 0){
                    oddNumber+=code[i];
                }else {
                    even+=code[i];
                }
            }
            combine = even * 3 + oddNumber;
        }else {
            /**  计算GTIN14校验码*/
            //偶数
            int even = 0;
            //奇数
            int oddNumber = 0;
            for(int i=0;i<code.length;i++){
                if(i % 2 == 0){
                    oddNumber = oddNumber + code[i];

                }else {
                    even = even + code[i];
                }
            }
            combine = oddNumber * 3 + even;
        }

        //求最小整倍数
        int multiple = 0;
        if(combine%10==0){
            return 0;
        }else {
            if (combine > 10 && (combine % 10 != 0)) {
                multiple = combine / 10 * 10 + 10;
            }
            System.out.println("----------------------------------->"+multiple+"-"+combine);
            return multiple - combine;
        }
    }
}
